﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Text;
using Dcms.BLL;
using Dcms.Model;
using Dcms.Common;
using System.Collections.Generic;
using System.Text.RegularExpressions;


public partial class Manage_Modle_ModelField_EditModelField : System.Web.UI.Page
{
    private IList<Dcms_RegexModel> iRegexList;

    /// <summary>
    /// 页面加载
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            GetModels();

            getPermission();

            BindData();
        }
    }

    /// <summary>
    /// 取得模块
    /// </summary>
    private void GetModels()
    {
        Dcms_ModelFieldBLL bllModelField = new Dcms_ModelFieldBLL();
        ddlPermission.DataSource = bllModelField.GetModels();
        ddlPermission.DataBind();
    }

    /// <summary>
    /// 绑定数据到GridView中
    /// </summary>
    private void BindData()
    {
        getRegex();

        Dcms_ModelFieldBLL lBll = new Dcms_ModelFieldBLL();
        gvModelField.DataSource = lBll.GetModelListByModelAndModelKeyID(txtModel.Text, Convert.ToInt32(txtModelKeyID.Text));
        gvModelField.DataBind();
    }

    /// <summary>
    /// 取得验证的内容
    /// </summary>
    private void getRegex()
    {
        Dcms_RegexBLL bll = new Dcms_RegexBLL();
        iRegexList = bll.GetModelList();
        Dcms_RegexModel mRegex = new Dcms_RegexModel();
        mRegex.RegexID = 0;
        mRegex.RegexName = "无";
        mRegex.RegexContent = "";
        iRegexList.Insert(0, mRegex);
    }

    /// <summary>
    /// GridView  RowDataBound
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void gvModelField_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            if (DataBinder.Eval(e.Row.DataItem, "mf_DisplayFlag").ToString() == "0")
            {
                for (int i = 0; i < e.Row.Cells.Count - 1; i++)
                {
                    e.Row.Cells[i].Enabled = false;
                }
            }
            RadioButtonList rblMF_DisplayFlag = (RadioButtonList)e.Row.FindControl("rblMF_DisplayFlag");
            rblMF_DisplayFlag.SelectedIndex = Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "mf_DisplayFlag"));

            DropDownList ddlMF_ValidateField = (DropDownList)e.Row.FindControl("ddlMF_ValidateField");
            ddlMF_ValidateField.DataSource = iRegexList;
            ddlMF_ValidateField.DataBind();

            ddlMF_ValidateField.Items.FindByValue(DataBinder.Eval(e.Row.DataItem, "mf_ValidateType").ToString()).Selected = true;


            CheckBox chkRequiredField = (CheckBox)e.Row.FindControl("chkRequiredField");
            chkRequiredField.Checked = Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "mf_RequiredField")) == 1;
        }
    }

    /// <summary>
    /// RowCommand处理
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void gvModelField_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "DisplayFlag")
        { 
            //改变状态
            Dcms_ModelFieldBLL bll = new Dcms_ModelFieldBLL();
            Dcms_ModelFieldModel model = bll.GetModelByID(Convert.ToInt32(e.CommandArgument.ToString()));
            model.mf_DisplayFlag = model.mf_DisplayFlag == 1 ? 0 : 1;
            bll.Update(model);
            BindData();
        }
        else if (e.CommandName == "IsMustField")
        {
            //修改该项是否为必选项
            Dcms_ModelFieldBLL bll = new Dcms_ModelFieldBLL();
            Dcms_ModelFieldModel model = bll.GetModelByID(Convert.ToInt32(e.CommandArgument.ToString()));
            model.mf_MustField = model.mf_MustField == 1 ? 0 : 1;
            bll.Update(model);
            BindData();
        }
    }

    /// <summary>
    /// 单行修改
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void gvModelField_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        //单行修改
        string strFieldID = gvModelField.Rows[e.RowIndex].Cells[0].Text;
        Dcms_ModelFieldBLL bll = new Dcms_ModelFieldBLL();
        Dcms_ModelFieldModel model = bll.GetModelByID(Convert.ToInt32(strFieldID));
        TextBox txtMF_FieldLabel = (TextBox)gvModelField.Rows[e.RowIndex].FindControl("txtMF_FieldLabel");
        model.mf_FieldLabel = txtMF_FieldLabel.Text;
        RadioButtonList rblMF_DisplayFlag = (RadioButtonList)gvModelField.Rows[e.RowIndex].FindControl("rblMF_DisplayFlag");
        model.mf_DisplayFlag = Convert.ToInt32(rblMF_DisplayFlag.SelectedValue);
        DropDownList ddlMF_ValidateField = (DropDownList)gvModelField.Rows[e.RowIndex].FindControl("ddlMF_ValidateField");

        //取验证
        int intRegexID = Convert.ToInt32(ddlMF_ValidateField.SelectedValue);
        model.mf_ValidateType = intRegexID;
        if (intRegexID > 0)
        {
            Dcms_RegexBLL bllRegex = new Dcms_RegexBLL();
            Dcms_RegexModel mRegex = bllRegex.GetModelByID(intRegexID);
            model.mf_ValidateField = mRegex.RegexContent;
            model.mf_RegexErrorMsg = mRegex.RegexErrorMsg;
        }
        else
        {
            model.mf_ValidateField = "";
            model.mf_RegexErrorMsg = "";
        }

        //必填
        CheckBox chkRequiredField = (CheckBox)gvModelField.Rows[e.RowIndex].FindControl("chkRequiredField");
        model.mf_RequiredField = chkRequiredField.Checked == true ? 1 : 0;

        TextBox txtMF_Order = (TextBox)gvModelField.Rows[e.RowIndex].FindControl("txtMF_Order");
        model.mf_Order = Convert.ToInt32(txtMF_Order.Text);

        bll.Update(model);

        //重新绑定
        BindData();
    }

    protected void ddlPermission_SelectedIndexChanged(object sender, EventArgs e)
    {
        getPermission();
        BindData();
    }

    /// <summary>
    /// 取得模块
    /// </summary>
    protected void getPermission()
    {
        Dcms_PermissionBLL bllPermission = new Dcms_PermissionBLL();
        Dcms_PermissionModel mPermission = bllPermission.GetModelByID(Convert.ToInt32(ddlPermission.SelectedValue));
        txtModel.Text = mPermission.Permission_Flag;
        txtModelKeyID.Text = mPermission.Permission_ModelKeyId.ToString();

        Dcms_CateBLL cBll = new Dcms_CateBLL();
        Dcms_CateModel cModel = cBll.GetModelByFlag(mPermission.Permission_Flag, mPermission.Permission_ModelKeyId, "CN");
        hidCatID.Value = cModel.Cate_ID.ToString();
        rblIsCommentFlag.SelectedIndex = cModel.Cate_IsCommentFlag;
        rblIsRevertFlag.SelectedIndex = cModel.Cate_IsRevertFlag;
    }

    /// <summary>
    /// 恢复默认
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    //protected void btnRenew_Click(object sender, EventArgs e)
    //{ 
    //    //string strXmlPath = Server.MapPath(@"~\Manage\Modle\ModelField\FilePath.xml");
    //    //DataSet ds = DcmsXmlHelper.GetXmlData(strXmlPath, "root");
    //    //DataTable dt = ds.Tables[0];
    //    //foreach (DataRow dr in dt.Rows)
    //    //{
    //    //    Response.Write(dr["DestPath"].ToString() + "<br/>");
    //    //    Response.Write(string.Format(dr["DestPath"].ToString(), "fdsafdsafdsf") + "<br/>");
    //    //    Response.Write(Server.MapPath(dr["DestPath"].ToString()) + "<br/>");
    //    //    return;
    //    //}
    //}

    #region 保存及生成
    /// <summary>
    /// 保存并生成
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnSaveAndCreate_Click(object sender, EventArgs e)
    {
        if (SaveData() == true)
        {
            CreateForm();
        }
    }

    /// <summary>
    /// 生成
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnCreate_Click(object sender, EventArgs e)
    {
        CreateForm();
    }

    /// <summary>
    /// 保存数据
    /// </summary>
    /// <returns></returns>
    private bool SaveData()
    {
        bool blnRef = false;
        try
        {
            //操作数据
            foreach (GridViewRow gvr in gvModelField.Rows)
            {
                string strFieldID = gvr.Cells[0].Text;
                Dcms_ModelFieldBLL bll = new Dcms_ModelFieldBLL();
                Dcms_ModelFieldModel model = bll.GetModelByID(Convert.ToInt32(strFieldID));
                TextBox txtMF_FieldLabel = (TextBox)gvr.FindControl("txtMF_FieldLabel");
                model.mf_FieldLabel = txtMF_FieldLabel.Text;
                RadioButtonList rblMF_DisplayFlag = (RadioButtonList)gvr.FindControl("rblMF_DisplayFlag");
                model.mf_DisplayFlag = Convert.ToInt32(rblMF_DisplayFlag.SelectedValue);
                DropDownList ddlMF_ValidateField = (DropDownList)gvr.FindControl("ddlMF_ValidateField");

                //取验证
                int intRegexID = Convert.ToInt32(ddlMF_ValidateField.SelectedValue);
                model.mf_ValidateType = intRegexID;
                if (intRegexID > 0)
                {
                    Dcms_RegexBLL bllRegex = new Dcms_RegexBLL();
                    Dcms_RegexModel mRegex = bllRegex.GetModelByID(intRegexID);
                    model.mf_ValidateField = mRegex.RegexContent;
                    model.mf_RegexErrorMsg = mRegex.RegexErrorMsg;
                }
                else
                {
                    model.mf_ValidateField = "";
                    model.mf_RegexErrorMsg = "";
                }

                //必填
                CheckBox chkRequiredField = (CheckBox)gvr.FindControl("chkRequiredField");
                model.mf_RequiredField = chkRequiredField.Checked == true ? 1 : 0;

                TextBox txtMF_Order = (TextBox)gvr.FindControl("txtMF_Order");
                model.mf_Order = Convert.ToInt32(txtMF_Order.Text);

                bll.Update(model);
            }
            blnRef = true;
        }
        catch (Exception ex)
        {
            Response.Write(ex.Message);
            //写日志
        }
        return blnRef;
    }

    /// <summary>
    /// 生成表单
    /// </summary>
    private void CreateForm()
    {
        #region 1。取得要显示的字段数据
        Dcms_ModelFieldBLL bllModelField = new Dcms_ModelFieldBLL();

        IList<Dcms_ModelFieldModel> ilistModelField = bllModelField.GetShowModelListByModelAndModelKeyID(txtModel.Text, Convert.ToInt32(txtModelKeyID.Text));
        #endregion

        #region 2。根据字段内容取得对应创建控件对象
        string strControls = "";
        string strBackground = "#FAFAFA";
        foreach(Dcms_ModelFieldModel mModelField in ilistModelField)
        {
            if (mModelField.mf_FieldInfo != "")
            {
                //取得帮助提示,当无帮助时不显示
                string strHelp = "";
                if (mModelField.mf_FieldHelpInfo != "")
                {
                    strHelp = "<img src=\"../../images/icon3.gif\" onmouseover='divShow(\"" + mModelField.mf_FieldHelpInfo + "\")' onmouseout=\"divHide()\" />";
                }

                //{0}-->背景色   {1}-->显示标签  {2}-->字段帮助  {3}-->正则  {4}-->错误信息
                if (mModelField.mf_ValidateField != "" && mModelField.mf_RequiredField == 1)
                {
                    strControls += string.Format(mModelField.mf_FieldInfo, strBackground, mModelField.mf_FieldLabel, strHelp, mModelField.mf_ValidateField, mModelField.mf_RegexErrorMsg);
                }
                else
                {
                    string strFieldInfo = mModelField.mf_FieldInfo;
                    if (mModelField.mf_RequiredField == 0)
                    {
                        //过滤必填
                        Regex regex = new Regex(@"<asp:RequiredFieldValidator [^>]*>[\s]*</asp:RequiredFieldValidator>");
                        strFieldInfo = regex.Replace(strFieldInfo, "");
                    }
                    if (mModelField.mf_ValidateField == "")
                    {
                        //过滤验证
                        Regex regex = new Regex(@"<asp:RegularExpressionValidator [^>]*>[\s]*</asp:RegularExpressionValidator>");
                        strFieldInfo = regex.Replace(strFieldInfo, "");
                    }
                    strControls += string.Format(strFieldInfo, strBackground, mModelField.mf_FieldLabel, strHelp, mModelField.mf_ValidateField, mModelField.mf_RegexErrorMsg);
                }
                strBackground = strBackground == "#FAFAFA" ? "#F2F2F2" : "#FAFAFA";
            }
        }
        #endregion

        #region 3。取得模板路径及保存路径
        string strEditTemplatePath = "";
        string strEditDestPath = "";
        string strListTemplatePath = "";
        string strListDestPath = "";

        if (GetTemplatePath(txtModel.Text, out strEditTemplatePath, out strEditDestPath, out strListTemplatePath, out strListDestPath) == false)
        { 
            //出错
            RegisterClientScriptBlock("", "alert('取模板路径时出错，请联系管理员！');");
            return;
        }
        #endregion

        #region 4。取得模板
        string strFileContent = GetTemplate(strEditTemplatePath);
        #endregion

        #region 5。替换相关标签
        strFileContent = strFileContent.Replace("{Controls}", strControls);
        #endregion

        #region 6。保存文件
        //保存编辑页面
        strEditDestPath = string.Format(strEditDestPath, txtModelKeyID.Text);
        SaveFile(strEditDestPath, strFileContent);

        //保存列表页面
        strFileContent = GetTemplate(strListTemplatePath);
        strFileContent = strFileContent.Replace("{ModelKeyID}", txtModelKeyID.Text);
        strListDestPath = string.Format(strListDestPath, txtModelKeyID.Text);
        SaveFile(strListDestPath, strFileContent);
        #endregion
    }

    /// <summary>
    /// 保存文件
    /// </summary>
    /// <param name="strFileName"></param>
    /// <param name="strFileContent"></param>
    /// <returns></returns>
    private void SaveFile(string strFileName, string strFileContent)
    {
        using (FileStream fs = new FileStream(strFileName, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite))
        {
            try
            {
                Byte[] info = System.Text.Encoding.UTF8.GetBytes(strFileContent);
                fs.Write(info, 0, info.Length);
                fs.Close();
            }
            catch (Exception ex)
            {
            }
        }
    }

    /// <summary>
    /// 取得模板路径及保存对应的路径
    /// </summary>
    /// <param name="strModelName">模块名称</param>
    /// <param name="strEditTemplatePath">编辑模板</param>
    /// <param name="strEditDestPath">编辑页面保存路径</param>
    /// <param name="strListTemplatePath">列表模板</param>
    /// <param name="strListDestPath">列表页面保存路径</param>
    /// <returns></returns>
    private bool GetTemplatePath(string strModelName, out string strEditTemplatePath, out string strEditDestPath, out string strListTemplatePath, out string strListDestPath)
    {
        bool blnRef = false;
        strEditTemplatePath = "";
        strEditDestPath = "";
        strListTemplatePath = "";
        strListDestPath = "";
        try
        {
            string strXmlPath = Server.MapPath(@"~\Manage\Modle\ModelField\FilePath.xml");
            DataSet ds = DcmsXmlHelper.GetXmlData(strXmlPath, "root");
            if (ds != null && ds.Tables.Count > 0)
            {
                DataTable dt = ds.Tables[0];
                foreach (DataRow dr in dt.Rows)
                {
                    if (string.Compare(dr["name"].ToString(), strModelName, true) == 0)
                    {
                        switch (dr["PageType"].ToString().ToLower())
                        { 
                            case "edit":
                                strEditTemplatePath = Server.MapPath(dr["TemplatePath"].ToString());
                                strEditDestPath = Server.MapPath(dr["DestPath"].ToString());
                                break;
                            case "list":
                                strListTemplatePath = Server.MapPath(dr["TemplatePath"].ToString());
                                strListDestPath = Server.MapPath(dr["DestPath"].ToString());
                                break;
                            default:
                                break;
                        }
                    }
                }
            }
            blnRef = true;
        }
        catch
        {
        }
        return blnRef;
    }

    /// <summary>
    /// 取得模板内容
    /// </summary>
    private string GetTemplate(string strFilePath)
    {
        string strTemplateText = "";

        //如果指定风格的模板文件不存在...
        if (System.IO.File.Exists(strFilePath))
        {
            using (System.IO.StreamReader objReader = new System.IO.StreamReader(strFilePath, Encoding.UTF8))
            {
                //读取开始
                StringBuilder textOutput = new StringBuilder();
                textOutput.Append(objReader.ReadToEnd());
                objReader.Close();
                strTemplateText = textOutput.ToString();
            }
        }
        return strTemplateText;
    }

    /// <summary>
    /// 创建控件
    /// </summary>
    /// <param name="dr"></param>
    /// <returns></returns>
    private string CreateControl(DataRow dr)
    {
        string strCtl = (string)dr["FieldInfo"];
        strCtl = string.Format(strCtl, dr["FieldLabel"]);
        return strCtl;
    }
    #endregion

    /// <summary>
    /// 设置评论
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnSet_Click(object sender, EventArgs e)
    {
        Dcms_CateBLL cBll = new Dcms_CateBLL();
        Dcms_CateModel cModel = cBll.GetModelByID(Int32.Parse(hidCatID.Value));
        cModel.Cate_IsCommentFlag = rblIsCommentFlag.SelectedIndex;
        cModel.Cate_IsRevertFlag = rblIsRevertFlag.SelectedIndex;
        cBll.Update(cModel);
        BindData();
    }
    protected void rblIsCommentFlag_SelectedIndexChanged(object sender, EventArgs e)
    {
        rblIsRevertFlag.SelectedIndex = rblIsCommentFlag.SelectedIndex;
        rblIsRevertFlag.Enabled = rblIsCommentFlag.SelectedIndex == 1;
        BindData();
    }
}
